package net.flintx.array;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by flintx on 2018/1/3.
 */
public class TwoSum {


    public static int[] twoSum(int[] nums, int target){
        /**
         * twoSum
         *
         * @Description:
         *  Given an array of integers, return indices of the two numbers such that they add up to a specific target.
         *  You may assume that each input would have exactly one solution, and you may not use the same element twice.
         * @Example:
         *  Given nums = [2, 7, 11, 15], target = 9,
         *  Because nums[0] + nums[1] = 2 + 7 = 9,
         *  return [0, 1].
         * @Params: [nums, target]
         * @Return: int[]
         * @Date: 2018/1/4
         */
        Map<Integer, Integer> m = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            m.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int diff = target - nums[i];
            if (m.containsKey(diff) && m.get(diff) != i) {
                int[] res = {Math.min(i, m.get(diff)), Math.max(i, m.get(diff))};
                return res;
            }
        }
        return null;
    }


    public static void main(String[] args) {
        int[] nums = {3,2,4};
        int target = 6;
        System.out.println(Arrays.toString(twoSum(nums, target)));
    }
}
